# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
import subprocess

from conans import ConanFile, tools, CMake


class CaresConan(ConanFile):
    name = "c_ares"
    description = "A C library for asynchronous DNS requests"
    license = "MIT"
    settings = "os", "arch", "compiler", "build_type"
    generators = "cmake_find_package"
    _cmake = None
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "tools": [True, False]
    }
    default_options = {
        "shared": False,
        "fPIC": True,
        "tools": False
    }

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    def source(self):
        git = tools.Git(verify_ssl=False)
        git.clone(**self.conan_data["sources"][self.version])

    def build(self):
        cmake = self._configure_cmake()
        cmake.build()

    def package(self):
        cmake = self._configure_cmake()
        cmake.install()
        self.copy("permissions.ini", src="", dst="")

    def package_info(self):
        self.cpp_info.libs = ["cares"]
        self.env_info.libdirs = ["lib"]
        self.env_info.includedirs = ["include"]

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)
        os.environ['CFLAGS'] = os.getenv('CFLAGS') + " -D_FORTIFY_SOURCE=2 -O2 -w"
        os.environ['CXXFLAGS'] = os.getenv('CXXFLAGS') + " -D_FORTIFY_SOURCE=2 -O2"
        self._cmake.definitions["CARES_BUILD_TESTING"] = "OFF"
        self._cmake.definitions["CARES_STATIC"] = not self.options.shared
        self._cmake.definitions["CARES_SHARED"] = self.options.shared
        self._cmake.definitions["CARES_BUILD_TOOLS"] = self.options.tools
        self._cmake.definitions["CMAKE_CXX_STANDARD"] = 17
        self._cmake.definitions["CARES_INSTALL"] = True
        self._cmake.definitions["CARES_STATIC_PIC"] = self.options.fPIC
        self._cmake.configure(args=["--no-warn-unused-cli"])
        return self._cmake